package com.idbk.chargestation;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.idbk.chargestation.app.ManagerADs;
import com.idbk.chargestation.app.ManagerUpdate;
import com.idbk.chargestation.base.CheckPermissionsActivity;
import com.idbk.chargestation.bean.JsonMyMessage;
import com.idbk.chargestation.db.MessageDatabase;
import com.idbk.chargestation.fragment.FragmentCharge;
import com.idbk.chargestation.fragment.FragmentMap;
import com.idbk.chargestation.fragment.FragmentPersonalInfo;
import com.idbk.chargestation.service.DemoIntentService;
import com.idbk.chargestation.service.PushMessageReceiver;
import com.idbk.chargestation.util.Const;
import com.igexin.sdk.PushManager;

import java.util.List;

/**
 * 主界面
 *
 * @author lupc, liangzw, zhx
 */
public class MainActivity extends CheckPermissionsActivity implements OnClickListener {

    protected static final String TAG = MainActivity.class.getSimpleName();
    private FragmentMap fragmentMap;
    private FragmentCharge fragmentCharge;
    private FragmentPersonalInfo fragmentUser;
    private LinearLayout tabMap;
    private TextView tvTabMap, tvTabCharge, tvTabUser;//tab
    private ImageView ivMessageTip;
    private Context mContext;
    private long exitTime = 0;
    private ImageView mImageMe;
    private Toast mToast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        mContext = MainActivity.this;

        setupView();

        setupData();

        initOther();
    }

    private void setupView() {
        fragmentMap = (FragmentMap) getSupportFragmentManager().findFragmentById(R.id.fragment_map);
        fragmentCharge = (FragmentCharge) getSupportFragmentManager().findFragmentById(R.id.fragment_charge);
        fragmentUser = (FragmentPersonalInfo) getSupportFragmentManager().findFragmentById(R.id.fragment_user);
        //
        tabMap = (LinearLayout) findViewById(R.id.tab_btn_map);
        tabMap.setOnClickListener(this);
        findViewById(R.id.tab_btn_charing).setOnClickListener(this);
        findViewById(R.id.tab_btn_mine).setOnClickListener(this);
        //
        tvTabMap = (TextView) findViewById(R.id.activity_main_textview_map);
        tvTabCharge = (TextView) findViewById(R.id.activity_main_textview_charge);
        tvTabUser = (TextView) findViewById(R.id.activity_main_textview_user);
        ivMessageTip = (ImageView) findViewById(R.id.imageview_messagetip);

        mImageMe = (ImageView) findViewById(R.id.imageview_tab_me);
    }

    private void setupData() {
        tabMap.performClick();

        PackageManager pkgManager = getPackageManager();
        // 读写 sd card 权限非常重要, android6.0默认禁止的, 建议初始化之前就弹窗让用户赋予该权限
        boolean sdCardWritePermission =
                pkgManager.checkPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        // read phone state用于获取 imei 设备信息
        boolean phoneSatePermission =
                pkgManager.checkPermission(android.Manifest.permission.READ_PHONE_STATE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        if (isNeedRequestPermission(sdCardWritePermission, phoneSatePermission)) {
            requestPermission();
        } else {
            PushManager.getInstance().initialize(this.getApplicationContext(), PushMessageReceiver.class);
        }
        //注册
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), DemoIntentService.class);
    }

    private boolean isNeedRequestPermission(boolean sdCardWritePermission, boolean phoneSatePermission) {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !sdCardWritePermission || !phoneSatePermission;
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[] {
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        android.Manifest.permission.READ_PHONE_STATE
                        }, Build.VERSION_CODES.M);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == Build.VERSION_CODES.M) {
            if ((grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
                PushManager.getInstance().initialize(this.getApplicationContext(), PushMessageReceiver.class);
            } else {
                Log.e(TAG, "We highly recommend that you need to grant the special permissions before initializing the SDK, otherwise some "
                        + "functions will not work");
                PushManager.getInstance().initialize(this.getApplicationContext(), PushMessageReceiver.class);
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private void initOther() {
        //检查更新(后台检查)
        new ManagerUpdate(this, false).checkUpdate();
        //更新广告数据
        new ManagerADs(getApplicationContext()).refresh();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mToast != null) {
            mToast.cancel();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tab_btn_map:
                getSupportFragmentManager()   //获得fragmentManage对象
                        .beginTransaction()           //开启事件
                        .hide(fragmentCharge).hide(fragmentUser).show(fragmentMap)   //设置显示
                        .commit();//提交
                tvTabMap.setTextColor(ContextCompat.getColor(mContext, R.color.tj_tabbar_title_active));
                tvTabMap.setCompoundDrawablesWithIntrinsicBounds(null,
                        ContextCompat.getDrawable(MainActivity.this, R.drawable.btn_tabbar_map_active),
                        null,
                        null);

                tvTabCharge.setTextColor(ContextCompat.getColor(mContext, R.color.tj_tabbar_title_normal));
                tvTabCharge.setCompoundDrawablesWithIntrinsicBounds(null,
                        ContextCompat.getDrawable(MainActivity.this, R.drawable.btn_tabbar_charging_normal),
                        null,
                        null);

                tvTabUser.setTextColor(ContextCompat.getColor(mContext, R.color.tj_tabbar_title_normal));
                mImageMe.setImageResource(R.drawable.btn_tabbar_me_normal);
                break;
            case R.id.tab_btn_charing:
                getSupportFragmentManager()
                        .beginTransaction()
                        .hide(fragmentMap)
                        .hide(fragmentUser)
                        .show(fragmentCharge)
                        .commit();
                //
                tvTabMap.setTextColor(ContextCompat.getColor(mContext, R.color.tj_tabbar_title_normal));
                tvTabMap.setCompoundDrawablesWithIntrinsicBounds(null,
                        ContextCompat.getDrawable(MainActivity.this, R.drawable.btn_tabbar_map_normal),
                        null,
                        null);

                tvTabCharge.setTextColor(ContextCompat.getColor(mContext, R.color.tj_tabbar_title_active));
                tvTabCharge.setCompoundDrawablesWithIntrinsicBounds(null,
                        ContextCompat.getDrawable(MainActivity.this, R.drawable.btn_tabbar_charging_active),
                        null,
                        null);

                tvTabUser.setTextColor(ContextCompat.getColor(mContext, R.color.tj_tabbar_title_normal));
                mImageMe.setImageResource(R.drawable.btn_tabbar_me_normal);
                break;
            case R.id.tab_btn_mine:
                getSupportFragmentManager()
                        .beginTransaction()
                        .hide(fragmentMap)
                        .hide(fragmentCharge).show(fragmentUser)
                        .commit();
                //
                tvTabMap.setTextColor(ContextCompat.getColor(mContext, R.color.tj_tabbar_title_normal));
                tvTabMap.setCompoundDrawablesWithIntrinsicBounds(null,
                        ContextCompat.getDrawable(MainActivity.this, R.drawable.btn_tabbar_map_normal),
                        null,
                        null);

                tvTabCharge.setTextColor(ContextCompat.getColor(mContext, R.color.tj_tabbar_title_normal));
                tvTabCharge.setCompoundDrawablesWithIntrinsicBounds(null,
                        ContextCompat.getDrawable(MainActivity.this, R.drawable.btn_tabbar_charging_normal),
                        null,
                        null);

                tvTabUser.setTextColor(ContextCompat.getColor(mContext, R.color.tj_tabbar_title_active));
                mImageMe.setImageResource(R.drawable.btn_tabbar_me_active);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateStatus();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Const.CODE_REQUEST_POINT) {
            if (resultCode == RESULT_OK) {
                //传递给fragment
                fragmentMap.onActivityResult(requestCode, resultCode, data);
            }
        } else if (requestCode == Const.CODE_REQUEST_CITY && resultCode == Activity.RESULT_OK) {
            fragmentMap.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void updateStatus() {
        AppContext ac = AppContext.getInstance();
        if (!ac.isLogin()) {
            ivMessageTip.setVisibility(View.GONE);
            return;
        }

        MessageDatabase mDb = new MessageDatabase(this);
        List<JsonMyMessage> results = mDb.selectMessage(ac.getLoginUserName(), false);
        if (results != null && results.size() > 0) {
            ac.setHasUnreadMessage(true);
        } else {
            ac.setHasUnreadMessage(false);
        }
        mDb.close();

        if (ac.isHasUnreadMessage()) {
            ivMessageTip.setVisibility(View.VISIBLE);
        } else {
            ivMessageTip.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            mToast = Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT);
            mToast.show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }


}
